#include "EpilPrefixExpressionParser.h"
#include "EpilIdentifierExpressionCode.h"
#include "EpilExpressionParser.h"
#include "EpilParserException.h"
#include "EpilPointerHelper.h"


EpilPrefixExpressionParser::EpilPrefixExpressionParser( EpilTokenStream & tokens )
: EpilSyntaxParserBase( tokens )
{
}


void EpilPrefixExpressionParser::Parse()
{
	// prefixexp -> NAME | '(' expr ')'

	switch( this->GetTokens().GetCurrentToken().type )
	{
	case ETT_Identifier:
		{
			EpilIdentifierExpressionCode * identifier = new EpilIdentifierExpressionCode( this->GetTokens().GetCurrentToken().location );
			identifier->SetName( this->GetTokens().GetCurrentToken().text );
			m_expression = identifier;
			this->GetTokens().MoveToNext();
		}
		break;
	case ETT_OpenParenthese:
		{
			// Skip the '('
			this->GetTokens().MoveToNext();

			EpilExpressionParser exprParser( this->GetTokens() );
			exprParser.Parse();
			m_expression = exprParser.GetExpression();

			// Check the ')'
			if( this->GetTokens().GetCurrentToken().type == ETT_CloseParenthese )
			{
				this->GetTokens().MoveToNext();
			}
			else
			{
				EpilPointerHelper::SafeDelete( m_expression );
				throw EpilParserException( t("Expect \'(\'."), this->GetTokens().GetCurrentToken().location );
			}
		}
		break;
	default:
		throw EpilParserException( t("Unexpected symbol."), this->GetTokens().GetCurrentToken().location );
		break;
	}
}